<?php

namespace App\Http\Controllers;

use App\Common\HttpClient;
use App\Common\Sql;
use App\Common\Tool;
use App\Logic\MiGuLogic;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redis;

class Base extends Controller
{

    public $uid;

    public $param;

    public function __construct(Request $request)
    {
        $this->param = json_decode(Input::get('param'), true);
//        $this->param = Input::get('param');
        $this->uid   = Input::get('uid');
        //把当前请求对象赋值给工具类的静态属性
        Tool::$request = $request;
    }

    public function returnData($data = [], $code = 0, $desc = '')
    {
        return Tool::jsonHandle($data, $code, $desc);
    }

    public function returnError($code, $desc)
    {
        return Tool::jsonHandle([], $code, $desc);
    }


    //获取用户信息
    public function get_user_info($uid)
    {
        $row = Sql::select('t_player_info', [['id', $uid]]);
        if (empty($row[0])) {
            return false;
        }
        return $row[0];
    }

    //记录道具发放记录
    public function insert_user_earn_item_record($uid, $itemid, $num, $source = '', $comment = '')
    {
        DB::table('t_user_item_rec')->insert([
            'uid' => $uid,
            'item_id' => $itemid,
            'num' => $num,
            'source' => $source,
            'comment' => $comment,
        ]);
    }

    //获取用户某每日任务的未领取次数和已经完成次数
    public function get_user_task_status($uid, $taskid)
    {
        $cur_date      = date('Y-m-d', time());
        $unclaimed_key = 'task_unclaimed_' . (string)$taskid . '_' . $cur_date;
        $finished_key  = 'task_finished_' . (string)$taskid . '_' . $cur_date;
        return array(Redis::hGet($unclaimed_key, (string)$uid), Redis::hGet($finished_key, (string)$uid));
    }

    //每日任务完成次数加一次
    public function add_task_finish_num($uid, $taskid)
    {
        $cur_date     = date('Y-m-d', time());
        $finished_key = 'task_finished_' . (string)$taskid . '_' . $cur_date;
        Redis::hIncrBy($finished_key, (string)$uid, 1);
        Redis::expire($finished_key, 3600 * 24 * 2);
        return true;
    }

    //每日任务未领取次数加一次
    public function add_task_unclaimed_num($uid, $taskid)
    {
        $cur_date     = date('Y-m-d', time());
        $finished_key = 'task_unclaimed_' . (string)$taskid . '_' . $cur_date;
        Redis::hIncrBy($finished_key, (string)$uid, 1);
        Redis::expire($finished_key, 3600 * 24 * 2);
        return true;
    }

    //获取摇奖规则
    public function get_rand_item_rule($rule_id)
    {
        $row = Sql::select('t_rand_rule_conf', [['rule_id', $rule_id]], ['item_id', 'num', 'rand', 'is_notice']);
        if (empty($row)) {
            return [];
        }
        return $row;
    }

    //验证兑换券的信息
    public function check_card_info($item, $code)
    {
        $object = DB::table('t_user_discount_info')->where('id', $item)->where('status', 1)->first();
        if (empty($object)) {
            return 0;
        }
        if ($object->sign == $code) {
            return $object->item_id;
        }
    }

    //TODO 使用兑换券 该方法暂时没有被调用,如果被调用了的话,需要修改数据库操作改成Laravel形式
    public function use_card($item, $code)
    {
        DB::beginTransaction();
        $object = DB::table('t_user_discount_info')->lockForUpdate()->where('id', $item)->where('status', 1)->first(['sign']);
        if (empty($object) || $object->sign != $code) {
            return false;
        }
        if (DB::table('t_user_discount_info')->where('id', $item)->update(['status' => 0])) {
            DB::commit();
            return true;
        }
        DB::rollBack();
        return false;
    }

    //每日任务未领取次数减一次
    public function sub_task_unclaimed_num($uid, $taskid)
    {
        $cur_date      = date('Y-m-d', time());
        $unclaimed_key = 'task_unclaimed_' . (string)$taskid . '_' . $cur_date;
        $unclaimed     = (int)Redis::hGet($unclaimed_key, (string)$uid);
        if ($unclaimed >= 1) {
            Redis::hIncrBy($unclaimed_key, (string)$uid, -1);
            Redis::expire($unclaimed_key, 3600 * 24 * 2);
            return true;
        } else {
            return false;
        }
    }

    //获取用户充值任务的是否完成
    public function get_user_recharge_task_status($uid, $taskid)
    {
        $key = 'task_recharge_' . (string)$taskid;
        $ret = Redis::hGet($key, (string)$uid);
        if ($ret == false) {
            return false;
        } else {
            return ($ret == 'done');
        }
    }

    //完成用户充值任务
    public function finish_user_recharge_task($uid, $taskid)
    {
        $key = 'task_recharge_' . (string)$taskid;
        $ret = Redis::hSet($key, (string)$uid, 'done');
        return ($ret != false);
    }

    //增加一个滚动通知
    public function add_notice($msg)
    {
        try {
            DB::table('t_notice_info')->insert([
                'message' => $msg,
                'status' => 1,
                'type' => 1,
                'begin_time' => date('Y-m-d H:i:s'),
                'create_time' => date('Y-m-d H:i:s'),
            ]);
            return true;
        } catch (\Exception $exception) {
            return false;
        }
    }

    //获取某用户在时间段内充值了多少rmb
    public function get_user_recharge_num($uid, $begin_time, $end_time)
    {
        $object = DB::table('pay')
            ->where('order_status', 1)
            ->where('uid', $uid)
            ->whereBetween('update_time', [date('Y-m-d', $begin_time), date('Y-m-d', $end_time)])
            ->select(DB::raw('sum(price) as total'))
            ->first();
        if (empty($object)) {
            return 0;
        }
        return $object->total;

    }

    //根据ID获取一个道具的信息
    public function get_item_info($itemid)
    {
        $row = Sql::select('t_item_conf', [['id', $itemid]]);
        if (empty($row)) {
            return false;
        } else {
            return $row[0];
        }
    }

    //获取用户有多少个某道具
    public function get_user_item_num($uid, $itemid)
    {
        $num = DB::table('t_user_bag_info')->where('uid', $uid)->where('item_id', $itemid)->value('num');
        if (empty($num)) {
            return 0;
        }
        return $num;
    }

//    //TODO 获取商户信息(未被调用,调用的话需要修改)
//    public function get_business_info($business_id)
//    {
//        $row = $this->mysql->find("SELECT * FROM `t_business_conf` WHERE `id` = $business_id AND `status` = 1");
//        if (count($row) != 1) {
//            return false;
//        } else {
//            return $row[0];
//        }
//    }

    //某用户道具数量减少N个
    public function sub_user_item($uid, $itemid, $new_num)
    {
        DB::beginTransaction();
        try {
            $result = false;
            $num    = DB::table('t_user_bag_info')
                ->lockForUpdate()
                ->where('uid', $uid)
                ->where('item_id', $itemid)
                ->where('num', '>=', $new_num)
                ->value('num');
            if (!is_null($num)) {
                if (DB::table('t_user_bag_info')
                    ->where('uid', $uid)
                    ->where('item_id', $itemid)
                    ->update(['num' => $num - $new_num])
                ) {
                    $result = true;
                }
            }
            DB::commit();
            return $result;
        } catch (\Exception $exception) {
            DB::rollBack();
            return false;
        }
    }

    //某用户道具数量增加N个
    public function add_user_item($uid, $itemid, $num, $source = '', $comment = '')
    {
        DB::beginTransaction();
        try {
            DB::select("INSERT INTO `t_user_bag_info`(`uid`,`item_id`,`num`) VALUES($uid,$itemid,$num) ON DUPLICATE KEY UPDATE `num` = `num` + $num");
            $this->insert_user_earn_item_record($uid, $itemid, $num, $source, $comment);
            DB::commit();
            return true;
        } catch (\Exception $exception) {
            DB::rollBack();
            return false;
        }
    }

    //增加N个优惠券
    public function create_discount_card($item_id, $uid, $num = 1, $source = '', $comment = '')
    {
        DB::beginTransaction();
        $data = [];
        try {
            for ($i = 0; $i < $num; $i++) {
                $data[] = [
                    'item_id' => $item_id,
                    'uid' => $uid,
                    'sign' => $this->generate_number(6),
                    'create_time' => date('Y-m-d H:i:s', time()),
                    'status' => 1
                ];
            }
            DB::table('t_user_discount_info')->insert($data);
            $this->insert_user_earn_item_record($uid, $item_id, $num, $source, $comment);
            DB::commit();
            return true;
        } catch (\Exception $exception) {
            DB::rollBack();
            return false;
        }
    }

    //奖励一个物品 未知类型
    public function reward_item($uid, $reward_id, $num = 1, $source = '', $comment = '')
    {
        $reward_info = $this->get_item_info($reward_id);
        if ($reward_info == false) {
            return false;
        } else {
            if ((int)$reward_info['type'] == 4) {
                return $this->create_discount_card($reward_id, $uid, $num, $source, $comment);
            } else {
                return $this->add_user_item($uid, $reward_id, $num, $source, $comment);
            }
        }
    }

    //生成一个随机数
    public function generate_number($length = 6)
    {
        // 密码字符集，可任意添加你需要的字符
        $chars  = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $number = '';
        for ($i = 0; $i < $length; $i++) {
            $number .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        return $number;
    }

    //给用户发放金币
    public function grant_gold($uid, $num, $source = '', $comment = '')
    {
        DB::beginTransaction();
        try {
            $result = false;
            if (!is_null(DB::table('t_player_info')->lockForUpdate()->where('status', 1)->find($uid))) {
                if (DB::table('t_player_info')->where('id', $uid)->update(['gold' => DB::raw("gold + $num")])) {
                    $this->record_grant_gold($uid, $num, $source, $comment);
                    $result = true;
                }
            }
            DB::commit();
            return $result;
        } catch (\Exception $exception) {
            DB::rollBack();
            return false;
        }
    }

    //获取用户钻石数量
    public function get_user_diamonds($uid)
    {
        $object = DB::table('t_player_info')->where('id', $uid)->where('status', 1)->first(['diamonds']);
        if (empty($object)) {
            return 0;
        }
        return $object->diamonds;
    }

    //获取用户金币数量
    public function get_user_gold($uid)
    {
        $object = DB::table('t_player_info')->where('id', $uid)->where('status', 1)->first();
        if (empty($object)) {
            return 0;
        }
        return $object->gold;
    }


    //给用户发放钻石
    public function grant_diamonds($uid, $num, $source = '', $comment = '', $item_id, $operateTypeSub, $localPropDst)
    {
        if ($num <= 0) {
            return true;
        }
        $data              = [
            'gameId' => MiGuLogic::$gameID,
            'timestamp' => (string)Tool::msectime(),
            'userId' => Tool::getMiGuId($uid),
            'operateTypeSub' => $operateTypeSub,
            'localPropDst' => $localPropDst,
            'localPropNum' => $num,
            'localScaleNum' => 1,
            'thirdGameName' => '贵州麻将',
            'thirdPropId' => $item_id,
            'thirdPropName' => $num . $source,
            'thirdPropNum' => $num,
            'thirdScaleNum' => 1
        ];
        $data['signature'] = Tool::miGuSignature($data);
        $url               = env('MIGU_BASE_URL') . '/exchange/diamond';
        $response          = (new HttpClient())->MiGuPost($url, json_encode($data));
        $response          = json_decode($response, true);
        if ($response['returnCode'] == 000000) {
            $this->record_grant_diamonds($uid, $num, $source, $comment . ':' . $response['resultData']['serialNo']);
            return true;
        }
        return false;
    }


    //给用户减钻石
    public function sub_diamonds($migu_id, $uid, $num, $source = '', $comment = '', $item_id)
    {
        if ($num <= 0) {
            return true;
        }
        $data              = [
            'gameId' => MiGuLogic::$gameID,
            'timestamp' => (string)Tool::msectime(),
            'userId' => $migu_id,
            'operateTypeSub' => 2,
            'localPropDst' => 100004,
            'localPropNum' => $num,
            'localScaleNum' => 1,
            'thirdGameName' => '贵州麻将',
            'thirdPropId' => $item_id,
            'thirdPropName' => $num . $source,
            'thirdPropNum' => $num,
            'thirdScaleNum' => 1
        ];
        $data['signature'] = Tool::miGuSignature($data);
        $url               = env('MIGU_BASE_URL') . '/exchange/diamond';
        $response          = (new HttpClient())->MiGuPost($url, json_encode($data));
        $response          = json_decode($response, true);
        if ($response['returnCode'] == 000000) {
            $this->record_grant_diamonds($uid, -$num, $source, $comment . ':' . $response['resultData']['serialNo']);
            return true;
        }
        return false;
    }

    //给用户发放金币
    public function grant_golds($uid, $num, $source = '', $comment = '')
    {
        if ($num <= 0) {
            return true;
        }
        DB::beginTransaction();
        try {
            $result = false;
            $gold   = DB::table('t_player_info')->lockForUpdate()->where('id', $uid)->where('status', 1)->value('gold');
            if (!is_null($gold)) {
                if (DB::table('t_player_info')->where('id', $uid)->update(['gold' => $gold + $num])) {
                    $this->record_grant_gold($uid, $num, $source, $comment);
                    $result = true;
                }
            }
            DB::commit();
            return $result;
        } catch (\Exception $exception) {
            DB::rollBack();
            return false;
        }
    }

//    //TODO 给用户减金币(未必调用,调用需修改)
//    public function sub_golds($uid, $num, $source = '', $comment = '')
//    {
//        if ($num <= 0) return true;
//        $this->mysql->query("BEGIN");
//        $sql    = "SELECT * FROM `t_player_info` WHERE `id` = $uid AND `status` = 1 FOR UPDATE";
//        $row    = $this->mysql->find($sql);
//        $result = false;
//        //如果钱足够
//        if (count($row) == 1) {
//            if ($row[0]["gold"] >= $num) {
//                $ret = $this->mysql->query("UPDATE `t_player_info` SET `gold` = `gold` - $num WHERE `id` = $uid");
//                if ($ret) {
//                    $this->record_grant_gold($uid, -$num, $source, $comment);
//                    $this->mysql->query("COMMIT");
//                    $result = true;
//                } else {
//                    $this->mysql->query("ROLLBACK");
//                }
//            }
//        }
//        $this->mysql->query("END");
//        return $result;
//    }

    //记录用户获得金币
    public function record_grant_gold($uid, $num, $source = '', $comment = '')
    {
        return DB::table('t_user_gold_rec')->insert([
            'uid' => $uid,
            'num' => $num,
            'source' => $source,
            'comment' => $comment
        ]);
    }

    //记录用户获得钻石
    public function record_grant_diamonds($uid, $num, $source = '', $comment = '')
    {
        return DB::table('t_user_diamonds_rec')->insert([
            'uid' => $uid,
            'num' => $num,
            'source' => $source,
            'comment' => $comment
        ]);
    }

//    //TODO 使用开房卡建立一个新房间(未被使用,使用需要修改)
//    public function create_new_room($uid, $player_num, $board_choose, $use_cards)
//    {
//        $password = $this->generate_number(8);
//        $para     = array('uid' => $uid, 'player_num' => $player_num, 'board_choose' => $board_choose, 'use_cards' => $use_cards, 'password' => $password);
//        return array('id' => $this->mysql->insert('t_create_room_rec', $para), 'password' => $password);
//    }
//
//    //TODO 解散房间(未被使用,使用需修改)
//    public function dissolution_room($uid, $id)
//    {
//        $ret = $this->mysql->query("UPDATE `t_create_room_rec` SET `status` = 3 WHERE `id` = $id AND `status` = 1");
//        if (1 == mysql_affected_rows()) {
//            return true;
//        } else {
//            return false;
//        }
//    }

}